package com.dfiov.cloud.msmtools.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.dfiov.cloud.msmtools.mapper.msbluetooth",
        sqlSessionTemplateRef = "msbluetoothSqlSessionTemplate",
        sqlSessionFactoryRef = "msbluetoothSqlSessionFactory")
public class MsBluetoothDataSourceConfig {
    @Bean(name = "msbluetoothDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.msbluetooth")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "msbluetoothSqlSessionFactory")
    public SqlSessionFactoryBean sqlSessionFactory(@Qualifier("msbluetoothDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/msbluetooth/*.xml"));
        return sqlSessionFactoryBean;
    }

    @Bean(name = "msbluetoothSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("msbluetoothSqlSessionFactory") SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryBean.getObject());
    }

    @Bean("msbluetoothDataSourceTransactionManager")
    public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("msbluetoothDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}